<!-- components/AddOrUpdate.vue -->
<template>
  <a-modal
      :title="formData.id ? '编辑部门' : '新增部门'"
      :visible="visible"
      :mask-closable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" layout="vertical" :rules="rules">
      <a-form-item label="部门名称" field="deptName">
        <a-input v-model="formData.deptName" placeholder="请输入部门名称" />
      </a-form-item>

      <a-form-item label="部门编码" field="deptCode">
        <a-input v-model="formData.deptCode" placeholder="请输入部门编码" />
      </a-form-item>

      <a-form-item label="部门描述" field="deptDesc">
        <a-textarea
            v-model="formData.deptDesc"
            placeholder="请输入部门描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>

      <a-form-item label="排序号" field="sort">
        <a-input-number
            v-model="formData.sort"
            placeholder="请输入排序号"
            :min="1"
            :precision="0"
            class="w-full"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useDeptStore } from '@/stores/dept';

const props = defineProps({
  visible: Boolean,
  deptData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'refresh']);

const deptStore = useDeptStore();
const formRef = ref(null);
const formData = reactive({
  id: undefined,
  deptName: '',
  deptCode: '',
  deptDesc: '',
  sort: 1
});

// 表单验证规则
const rules = {
  deptName: [{ required: true, message: '部门名称不能为空' }],
  deptCode: [{ required: true, message: '部门编码不能为空' }],
  sort: [{ required: true, message: '排序号不能为空' }]
};

// 监听传入的部门数据变化
watch(() => props.deptData, (newVal) => {
  Object.assign(formData, newVal);
}, { deep: true, immediate: true });

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const error = await formRef.value.validate();
    if (error) return;

    const isEdit = !!formData.id;

    if (isEdit) {
      await deptStore.updateDept(formData);
      Message.success('部门更新成功');
    } else {
      await deptStore.addDept(formData);
      Message.success('部门添加成功');
    }

    // 关闭弹窗并刷新列表
    emit('update:visible', false);
    emit('refresh');

  } catch (error) {
    console.error('操作失败:', error);
    Message.error(`操作失败: ${error.message || '请重试'}`);
  }
};

// 取消操作
const handleCancel = () => {
  formRef.value.resetFields();
  emit('update:visible', false);
};
</script>

<style scoped>
.w-full {
  width: 100%;
}
</style>